package com.tequila.core.service.impl;

import com.google.common.collect.Maps;
import com.tequila.core.service.FileService;
import com.tequila.core.service.SystemService;
import com.tequila.domain.dto.UploadFileDto;
import com.tequila.domain.entity.File;
import fe.core.aliyun.AliyunOssFileService;
import fe.core.aliyun.OSSUploadResult;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.UUID;

/**
 * Created by fe on 2017/7/26.
 */
@Service
public class SystemServiceImpl implements SystemService {

    public static final Logger   logger = LoggerFactory.getLogger(SystemServiceImpl.class);


    @Resource
    private AliyunOssFileService aliyunOssFileService;

    @Resource
    private FileService fileService;

    public Map<String, Object> upload(UploadFileDto uploadFileDto) {
        String originalFile = uploadFileDto.getOriginalFileName();

        String suffix = "jpg";
        if (StringUtils.isNotEmpty(originalFile)) {
            String[] fileNameStr = originalFile.split("\\.");
            if (StringUtils.isNotEmpty(fileNameStr[1])) {
                suffix = fileNameStr[1];
            }
        }

        String bucket = "";
        String category = "";
        if (StringUtils.isEmpty(uploadFileDto.getBucket())) bucket = "xiaofuli";

        if (StringUtils.isEmpty(category)) category = "xiaofuliImage";

        String unqFileName = UUID.randomUUID().toString();
        OSSUploadResult ossUploadResult = aliyunOssFileService.uploadFile(uploadFileDto.getInputStream(), suffix, bucket, originalFile, unqFileName,
                                                                          uploadFileDto.getContentType());

        File f = new File();
        f.setBucket(bucket);
        f.setFullName(originalFile);
        f.setFileLength((long) uploadFileDto.getData().length);
        f.setContentType(uploadFileDto.getContentType());
        f.setCategory(category);
        f.setUnqFileName(unqFileName + "." + suffix);
        fileService.saveFile(f);
        Map<String, Object> map = Maps.newHashMap();
        map.put("fileId", f.getId());
        map.put("fileUrl", aliyunOssFileService.getOSSFileUrl(ossUploadResult));

        return map;
    }

}
